<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <el-row :gutter="8">
        <el-col :span="8">
          <!-- 搜索框 -->
          <el-input
            placeholder="请输入内容"
            clearable
            v-model="queryInfo.query"
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogvisable = true">
            添加用户
          </el-button>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <el-table :data="userList" :border="true">
        <el-table-column type="index" label="#"> </el-table-column>

        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column
        ><el-table-column prop="mobile" label="电话"> </el-table-column
        ><el-table-column prop="role_name" label="角色"> </el-table-column
        ><el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column prop="create_time" label="操作">
          <template slot-scope="scope">
            <!-- 修改用户 -->
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除用户 -->
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="RemoveUserByid(scope.row.id)"
            ></el-button>
            <!-- 角色 -->
            <el-tooltip effect="dark" content="分配角色" placement="top">
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-setting"
                @click="showRoleDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页功能 -->

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 4, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogvisable"
      width="30%"
      @close="addDialogClose"
    >
      <!-- 内容区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="dialogForm"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogvisable = false">取 消</el-button>
        <el-button type="primary" @click="AddUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->

    <el-dialog title="修改用户" :visible.sync="EditShowDialog" width="50%">
      <!-- 修改内容 -->
      <el-form
        :model="editfrom"
        :rules="editfromRules"
        ref="editfromRef"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editfrom.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editfrom.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editfrom.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="EditShowDialog = false">取 消</el-button>
        <el-button type="primary" @click="EditUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->

    <el-dialog
      @close="selectRolesID = ''"
      title="分配角色"
      :visible.sync="RolesdialogVisible"
      width="50%"
    >
      <div>当前的用户：{{ userinfo.username }}</div>
      <div>当前的角色：{{ userinfo.role_name }}</div>
      <div>
        设置角色：
        <el-select v-model="selectRolesID" clearable placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="RolesdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRolesInfo()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {

  data() {

    // 自定义校验规则
    let checkemail = (rule, value, cb) => {
      const rex = /^([a-zA-z0-9_-])+@([a-zA-z0-9_-])+(\.[a-zA-z0-9_-])+/
      // console.log(rex.test(value))
      if (rex.test(value)) {
        //合法的邮箱

        return cb()
      }
      cb(new Error('请输入合法邮箱'))
    }
    let checkmobel = (rule, value, cb) => {
      const rexmobile = /^1[3456789]\d{9}$/
      if (rexmobile.test(value)) {
        //合法的邮箱

        return cb()

      }
      cb(new Error('请输入合法手机号'))
    }

    return {
      queryInfo: {
        query: '',
        //当前显示的页
        pagenum: 1,
        //当前每页显示多少条数据
        pagesize: 2
      },
      total: 0,
      userList: [],
      // 添加用户的显示与隐藏
      dialogvisable: false,
      // 修改用户的显示与隐藏
      EditShowDialog: false,
      //查询到的修改用户信息
      editfrom: {},
      // 分配角色对话框的显示与隐藏
      RolesdialogVisible: false,
      //分配角色的用户信息
      userinfo: {},
      //角色列表信息
      rolesList: [],
      //选中的角色id
      selectRolesID: "",


      // 添加用户对象


      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",

      },

      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 8, message: '用户名长度在 3 到 8个字符', trigger: 'blur' }
        ]
        ,
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },

        ],
        email: [
          { required: true, message: '请输入邮箱啊', trigger: 'blur' },
          { validator: checkemail, trigger: 'blur' },


        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkmobel, trigger: 'blur' },


        ]
      }
      ,
      editfromRules: {
        email: [
          { required: true, message: '请输入邮箱啊', trigger: 'blur' },
          { validator: checkemail, trigger: 'blur' },


        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkmobel, trigger: 'blur' },


        ]
      }

    }
  },

  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message({ showClose: true, message: '获取数据失败', type: 'error' })
      }
      this.userList = res.data.users,
        this.total = res.data.total


    },
    handleSizeChange(nwepagesize) {
      //  监听每页显示多少条数据在重新发起请求，得到新的数据
      this.queryInfo.pagesize = nwepagesize
      this.getUserList()



    },
    handleCurrentChange(newpagenum) {
      //监听改变的页数 在重新获取数据 那一页的数据
      this.queryInfo.pagenum = newpagenum
      this.getUserList()
    },
    // 更改开关状态
    async userStateChange(changeSwicth) {
      // console.log(changeSwicth)
      const { data: res } = await this.$http.put(`users/${changeSwicth.id}/state/${changeSwicth.mg_state}`)
      if (res.meta.status !== 200) {
        return this.$message({ showClose: true, message: '更新失败', type: 'error' })

      }
      this.$message({ showClose: true, message: '更新状态成功', type: 'success' })
    },
    //关闭添加对话框 清空表单
    addDialogClose() {
      this.$refs.dialogForm.resetFields()
    },
    //添加表单用户
    AddUser() {
      //提交之前有个预验证
      this.$refs.dialogForm.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status != 201) {
          return this.$message({ showClose: true, message: '添加用户失败', type: 'error' })


        }
        this.$message({ showClose: true, message: '添加用户成功', type: 'success' })
        //关闭对话框
        this.dialogvisable = false
        //重新请求数据
        this.getUserList()
      })

    },
    // 修改用户id
    async showEditDialog(id) {

      const { data: res } = await this.$http.get('users/' + id)

      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message({ showClose: true, message: '获取数据失败', type: 'error' })

      }
      this.editfrom = res.data
      //打开修改对话框
      this.EditShowDialog = true


    },
    // 修改用户
    EditUser() {
      this.$refs["editfromRef"].validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put('users/' + this.editfrom.id, {
          email: this.editfrom.email,
          mobile: this.editfrom.mobile
        })
        // console.log(res)
        if (res.meta.status !== 200) {
          return this.$message({ showClose: true, message: '修改失败', type: 'error' })

        }
        // 提示修改成功
        this.$message({ showClose: true, message: '修改用户成功', type: 'success' })

        // 更新数据
        this.getUserList()
        // 关闭对话框

        this.EditShowDialog = false

      })
    },
    // 删除用户

    async RemoveUserByid(id) {

      const resConfirm = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).catch(err => err)

      // 确定返回confirm字符串
      // 取消就返回 cancel字符串
      // console.log(res)
      if (resConfirm !== 'confirm') {
        return this.$message({ showClose: true, message: '已取消删除', type: 'info' })

      }

      const { data: res } = await this.$http.delete('users/' + id)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message({ showClose: true, message: res.meta.msg, type: 'error' })

      }
      this.$message({ showClose: true, message: res.meta.msg, type: 'success' })
      //更新数据
      this.getUserList()

      //分配角色的对话框



    },
    async showRoleDialog(userinfo) {
      this.userinfo = userinfo

      const { data: res } = await this.$http.get('roles')
      console.log(res)
      if (res.meta.status != 200) {
        return this.$message({ showClose: true, message: res.meta.msg, type: 'error' })

      }

      this.rolesList = res.data





      this.RolesdialogVisible = true
      // console.log(this.userinfo)
    },
    //保存分配角色的信息
    async saveRolesInfo() {


      const { data: res } = await this.$http.put(`users/${this.userinfo.id}/role`, { rid: this.selectRolesID })
      if (res.meta.status != 200) {
        return this.$message({ showClose: true, message: res.meta.msg, type: 'error' })

      }
      this.$message({ showClose: true, message: res.meta.msg, type: 'success' })
      this.getUserList()
      this.RolesdialogVisible = false


    }




  }

}
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 15px !important;
}
</style>